import { ipcRenderer } from 'electron'
import {
  BATCH_ADD_SOURCES,
  GET_SOURCE,
  SOURCES_LIST,
  REMOVE_SOURCES,
  ADD_SOURCES,
  CALLBACK,
  DOWNLOAD_NOVEL,
  GET_NOVEL,
  NOVEL_LIST,
  REMOVE_NOVEL,
  UPDATE_NOVEL,
  GET_NOVEL_CHAPTER,
  CHANG_NOVEL_SOURCE,
  UPDATE_SOURCE,
  SEARCH_NOVEL,
  STOP_SEARCH_NOVEL,
  GEN_MOBI
} from 'novel-parser/servies/channel'

function request (url, params) {
  return new Promise((resolve, reject) => {
    ipcRenderer.once(url + CALLBACK, (event, arg) => {
      if (arg.code === 200) {
        resolve(arg.data)
      } else {
        reject(arg)
      }
    })
    ipcRenderer.send(url, params)
  })
}

export function getSource (params) {
  return request(GET_SOURCE, params)
}

export function getSourceList (params) {
  return request(SOURCES_LIST, params)
}

export function removeSource (params) {
  return request(REMOVE_SOURCES, params)
}

export function addSource (params) {
  return request(ADD_SOURCES, params)
}

export function downloadNovel (params) {
  return request(DOWNLOAD_NOVEL, params)
}

export function getNovel (params) {
  return request(GET_NOVEL, params)
}

export function getNovelList (params) {
  return request(NOVEL_LIST, params)
}

export function removeNovel (params) {
  return request(REMOVE_NOVEL, params)
}

export function updateNovelSource (params) {
  const { _id, ...update } = params
  return request(CHANG_NOVEL_SOURCE, { id: _id, update })
}

export function getNovelChapter (params) {
  return request(GET_NOVEL_CHAPTER, params)
}

export function updateNovel (params) {
  return request(UPDATE_NOVEL, params)
}

export function updateSource (params) {
  return request(UPDATE_SOURCE, params)
}

export function searchNovel (params) {
  ipcRenderer.send(SEARCH_NOVEL, params)
}

export function stopSearchNovel (params) {
  return request(STOP_SEARCH_NOVEL, params)
}

export function genMobi (id) {
  return request(GEN_MOBI, id)
}

export function batchAddSources (params) {
  return request(BATCH_ADD_SOURCES, params)
}
